package com.tianlang.freemarker.tag;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.tianlang.cache.Cache;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 自定义权限标签
 * 
 * @author mcp
 *
 */
public class AuthorityTag implements TemplateDirectiveModel {
	@SuppressWarnings("rawtypes")
	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		String value = params.get("value").toString();
		Map<String, Collection<ConfigAttribute>> resourceMap = Cache.resourceMap;
		SecurityContext context = SecurityContextHolder.getContext();
		Authentication authentication = (Authentication) context.getAuthentication();
		// 所请求的资源拥有的权限(一个资源对多个权限)
		Collection<ConfigAttribute> list = resourceMap.get(value);
		// 没有权限配置时 默认显示
		if (list == null || list.size() == 0) {
			body.render(env.getOut());
			return;
		}
		for (ConfigAttribute configAttribute : list) {
			// 访问所请求资源所需要的权限
			String needPermission = configAttribute.getAttribute();
			// 用户所拥有的权限authentication
			for (GrantedAuthority ga : authentication.getAuthorities()) {
				if (needPermission.equals((ga.getAuthority()))) {
					body.render(env.getOut());
					return;
				}
			}
		}
	}

}
